package com.orange.lockscreen.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;

import com.orange.lockscreen.SlatHashMap;
import com.orange.lockscreen.common.Constants.Music_Provider;
import com.orange.lockscreen.common.Constants.Notification_Provider;

public class LockScreenUtils {
	private static final String	TAG		= "LockScreenUtils";

	private static final String	ZERO	= "0";
	private static final String	SPACE	= " ";
	private static final String	COLON	= ":";

	public static Bitmap combineBitmaps(Bitmap backgroundBitmap,
			Bitmap widgetBitmap) {

		if (backgroundBitmap == null || widgetBitmap == null) {
			LogHelper.w(TAG,
					"combineBitmaps. backgroundBitmap|widgetBitmap are null.");
			return null;
		}

		Canvas canvas = new Canvas();

		int widgetWidth = widgetBitmap.getWidth();
		int widgetHeight = widgetBitmap.getHeight();

		int backWidth = backgroundBitmap.getWidth();
		int backHeight = backgroundBitmap.getHeight();
		int backDensity = backgroundBitmap.getDensity();

		Bitmap bitmap = null;
		try {
			bitmap = Bitmap.createBitmap(backWidth, backHeight,
					Config.ARGB_8888);
			bitmap.setDensity(backDensity);
			canvas.setBitmap(bitmap);
		} catch (OutOfMemoryError e) {
			LogHelper.e(TAG, "combineBitmaps. ", e);
		} catch (Exception e) {
			LogHelper.e(TAG, "combineBitmaps. ", e);
		}

		canvas.drawBitmap(backgroundBitmap, new Rect(0, 0, backWidth,
				backHeight), new Rect(0, 0, backWidth, backHeight), null);

		canvas.drawBitmap(widgetBitmap, new Rect(0, 0, widgetWidth,
				widgetHeight), new Rect(0, 0, backWidth, backHeight), null);

		widgetBitmap.recycle();

		return bitmap;
	}

	private static Bitmap splite(Bitmap src, int yOffset, int height,
			int actualHeight) {
		Bitmap bitmap = null;
		Canvas canvas;

		if (null != src) {
			int w = src.getWidth();
			int d = src.getDensity();
			canvas = new Canvas();

			try {
				bitmap = Bitmap.createBitmap(w, actualHeight, Config.ARGB_8888);
				bitmap.setDensity(d);
				canvas.setBitmap(bitmap);
			} catch (OutOfMemoryError e) {
				LogHelper.e(TAG, "splite. ", e);
			} catch (Exception e) {
				LogHelper.e(TAG, "splite. ", e);
			}

			canvas.drawBitmap(src, new Rect(0, yOffset, w, yOffset + height),
					new Rect(0, 0, w, actualHeight), null);
		}
		return bitmap;
	}

	public static Bitmap spliteBackground(Bitmap bgSrc) {
		if (null == bgSrc) {
			return null;
		}
		Bitmap bitmap = null;
		int bitmapHeight = bgSrc.getHeight();
		int screenHeight = SlatHashMap.getScreenHeight();
		if (bitmapHeight >= screenHeight) {
			int height = SlatHashMap.getScreenHeight();
			bitmap = splite(bgSrc, 0, height, height);
			bgSrc.recycle();
		} else {
			bitmap = bgSrc;
		}
		return bitmap;
	}

	public static Bitmap spliteSlideBitmap(Bitmap bgSrc, int rowIndex) {
		if (null == bgSrc) {
			return null;
		}
		int bitmapHeight = bgSrc.getHeight();
		int screenHeight = SlatHashMap.getScreenHeight();

		Bitmap bitmap = null;
		int slatHeight = SlatHashMap.getSlatHeight(rowIndex);
		int yOffset = SlatHashMap.getSlatTop(rowIndex);

		if (bitmapHeight >= screenHeight) {
			bitmap = splite(bgSrc, yOffset, slatHeight, slatHeight);
		} else {
			int scaleYOffset = (int) (yOffset * bitmapHeight / (float) screenHeight);
			int scaleSlatHeight = (int) (slatHeight * bitmapHeight / (float) screenHeight);

			bitmap = splite(bgSrc, scaleYOffset, scaleSlatHeight, slatHeight);
		}
		return bitmap;
	}

	public static int getScreenHeight(Context context) {
		Resources resource = context.getResources();
		Drawable phoneCallIcon = resource
				.getDrawable(android.R.drawable.stat_sys_phone_call);
		int notificationBarHeight = phoneCallIcon.getIntrinsicHeight();
		phoneCallIcon = null;
		int fullScreenHeight = resource.getDisplayMetrics().heightPixels;
		return fullScreenHeight - notificationBarHeight;
	}

	public static int getScreenWidth(Context context) {
		Resources resource = context.getResources();
		return resource.getDisplayMetrics().widthPixels;
	}

	/**
	 * add by gaoge 2011-11-25 for fix bug that lockscreen will squaled up
	 */
	public static LockscreenViewSize getScreenRealSize(Context context){
		Resources resource = context.getResources();
		int fullScreenHeight = resource.getDisplayMetrics().heightPixels;
		int fullScreenWidth = resource.getDisplayMetrics().widthPixels;
		
		Drawable phoneCallIcon = resource
		.getDrawable(android.R.drawable.stat_sys_phone_call);
		int notificationBarHeight = phoneCallIcon.getIntrinsicHeight();
		phoneCallIcon = null;
		
		if(fullScreenHeight < fullScreenWidth){
			int tmp = fullScreenHeight;
			fullScreenHeight = fullScreenWidth;
			fullScreenWidth = tmp;
		}
		return new LockscreenViewSize(fullScreenHeight - notificationBarHeight,fullScreenWidth);
		
	}
	/**
	 * add by gaoge 2011-11-25 for fix bug that lockscreen will squaled up
	 */
	public static class LockscreenViewSize{
		public LockscreenViewSize(int realHight,int realWidth){
			this.realHeight = realHight;
			this.realWidth = realWidth;
		}
		public int realHeight;
		public int realWidth;
	}
	public static void sendBroadcast(Context context, String action) {
		Intent intent = new Intent(action);
		
		try {
			context.sendBroadcast(intent);
		} catch (Exception e) {
			LogHelper.e(TAG, "sendBroadcast. ", e);
			// Should use "IllegalStateException", but trying to be safe.
		}
	}

	public static boolean isMusicTrackSelected(Context context) {
		ContentResolver resolver = context.getContentResolver();
		String[] projection = new String[] { Music_Provider.COLUMN_MUSIC_TRACK_SELECTED };
		Cursor cursor = null;
		try {
			cursor = resolver.query(Music_Provider.MUSIC_URI, projection, null,
					null, null);
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToNext();
				int selectIndex = cursor
						.getColumnIndex(Music_Provider.COLUMN_MUSIC_TRACK_SELECTED);
				String isSelected = cursor.getString(selectIndex);
				// return isSelected.equals("true") ? true : false;
				return "true".equals(isSelected) ? true : false;
			}
		} catch (Exception e) {
			LogHelper.e(TAG, "isMusicTrackSelected. ", e);
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		return false;
	}

	// public static int getNotificationCount(Context context){
	// ContentResolver resolver = context.getContentResolver();
	// String[] projection = new String[] {
	// Notification_Provider.COLUMN_NOTIFICATION_COUNT};
	// Cursor cursor = null;
	// int sumCount = 0;
	// try {
	// cursor = resolver.query(Notification_Provider.NOTIFICATION_URI,
	// projection, null,
	// null, null);
	// if (cursor != null && cursor.moveToNext()) {
	// int sumIndex = cursor
	// .getColumnIndex(Notification_Provider.COLUMN_NOTIFICATION_COUNT);
	// sumCount = cursor.getInt(sumIndex);
	// }
	// } catch (Exception e) {
	// Log.e(TAG, e.getMessage());
	// } finally {
	// if (cursor != null) {
	// cursor.close();
	// }
	// }
	//
	// return sumCount;
	// }

	// add by gaoge 2011-08-19 for fix bug 0013239
	public static List<Integer> getNotificationCount(Context context) {
		List<Integer> cnt_list = new ArrayList<Integer>();
		ContentResolver resolver = context.getContentResolver();
		String[] projection = new String[] {
				Notification_Provider.COLUMN_NOTIFICATION_COUNT,
				Notification_Provider.COLUMN_UNREADMMS_COUNT,
				Notification_Provider.COLUMN_MISSCALL_COUNT,
				Notification_Provider.COLUMN_VOICEMAI_COUNT };

		Cursor cursor = null;
		int sumCount = 0;
		int unreadMmsCnt = 0;
		int missCallCnt = 0;
		int voiceMailCnt = 0;

		try {
			cursor = resolver.query(Notification_Provider.NOTIFICATION_URI,
					projection, null, null, null);
			if (cursor != null && cursor.moveToNext()) {
				int sumIndex = cursor
						.getColumnIndex(Notification_Provider.COLUMN_NOTIFICATION_COUNT);
				int mmsIndex = cursor
						.getColumnIndex(Notification_Provider.COLUMN_UNREADMMS_COUNT);
				int miscallIndex = cursor
						.getColumnIndex(Notification_Provider.COLUMN_MISSCALL_COUNT);
				int voiceMailIndex = cursor
						.getColumnIndex(Notification_Provider.COLUMN_VOICEMAI_COUNT);

				sumCount = cursor.getInt(sumIndex);
				unreadMmsCnt = cursor.getInt(mmsIndex);
				missCallCnt = cursor.getInt(miscallIndex);
				voiceMailCnt = cursor.getInt(voiceMailIndex);

				cnt_list.add(sumCount);
				cnt_list.add(unreadMmsCnt);
				cnt_list.add(missCallCnt);
				cnt_list.add(voiceMailCnt);
			}
		} catch (Exception e) {
			LogHelper.e(TAG, "getNotificationCount. ", e);
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}

		return cnt_list;
	}

	public static boolean isPackageExist(Context context, String packageName) {
		try {
			context.getPackageManager().getPackageInfo(packageName,
					PackageManager.GET_ACTIVITIES);
		} catch (NameNotFoundException e) {
			return false;
		}
		return true;
	}

	public static String getDefaultHome(Context context) {
		String defaultName = null;
		List<ComponentName> prefActList = new ArrayList<ComponentName>();
		// Intent list cannot be null. so pass empty list
		List<IntentFilter> intentList = new ArrayList<IntentFilter>();
		context.getPackageManager().getPreferredActivities(intentList,
				prefActList, null);
		int prefActListSize = prefActList.size();
		if (prefActListSize != 0) {
			for (int i = 0; i < intentList.size(); i++) {
				if (Intent.CATEGORY_HOME.equals(intentList.get(i)
						.getCategory(0))) {
					defaultName = prefActList.get(i).getPackageName();
					break;
				}
			}
		}
		return defaultName;
	}

	public static String getDeviceType() {
		return Build.MODEL.toLowerCase(Locale.UK);
	}

	public static String[] spliteNextAlarm(String alarm) {
		String model = LockScreenUtils.getDeviceType();
		LogHelper.i(TAG, "spliteNextAlarm. model: " + model + " ,alarm: "
				+ alarm);
		if (model.contains(Constants.MODEL_ZTE)) {
			return spliteZTENextAlarm(alarm);
		} else {
			return spliteNexusNextAlarm(alarm);
		}
	}

	private static String[] spliteZTENextAlarm(String alarm) { // 24
		String[] ret = new String[] { "THU", "10:30 AM" };
		int spaceIndex = alarm.indexOf(SPACE);
		int colonIndex = alarm.indexOf(COLON);
		ret[0] = alarm.substring(spaceIndex + 1, spaceIndex + 4);

		String minuteTemp = alarm.substring(colonIndex + 1, colonIndex + 3);
		String minute = minuteTemp.toUpperCase();// 00AM

		String ampmTemp = alarm.substring(colonIndex + 3, spaceIndex - 1);
		String ampm = ampmTemp.toUpperCase();

		String lastHour = alarm.substring(colonIndex - 1, colonIndex);
		String firstHour = null;
		try {
			firstHour = alarm.substring(colonIndex - 2, colonIndex - 1);
		} catch (Exception e) {
			LogHelper.e(TAG, "spliteZTENextAlarm. ", e);
		}

		if (TextUtils.isEmpty(firstHour)) {
			firstHour = ZERO;
		}

		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(firstHour);
		stringBuffer.append(lastHour);
		stringBuffer.append(COLON);
		stringBuffer.append(minute);
		stringBuffer.append(SPACE);
		stringBuffer.append(ampm);
		ret[1] = stringBuffer.toString();
		LogHelper.i(TAG, "spliteZTENextAlarm. ret[1]: " + ret[1]);
		return ret;
	}

	private static String[] spliteNexusNextAlarm(String alarm) {
		String[] ret = new String[] { "THU", "10:30 AM" };
		int spaceIndex = alarm.indexOf(SPACE);
		int colonIndex = alarm.indexOf(COLON);
		int length = alarm.length();
		ret[0] = alarm.substring(0, spaceIndex);
		String minuteTemp = alarm.substring(colonIndex + 1, length);
		String minute = minuteTemp.toUpperCase();
		String lastHour = alarm.substring(colonIndex - 1, colonIndex);

		String firstHour = null;
		try {
			firstHour = alarm.substring(colonIndex - 2, colonIndex - 1);
			if (firstHour != null && firstHour.equals(SPACE)) {
				firstHour = ZERO;
			}
		} catch (Exception e) {
			LogHelper.e(TAG, "spliteNexusNextAlarm. ", e);
			firstHour = ZERO;
		}

		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(firstHour);
		stringBuffer.append(lastHour);
		stringBuffer.append(COLON);
		stringBuffer.append(minute);
		ret[1] = stringBuffer.toString();
		return ret;
	}
}
